package br.com.fatec.cqr.control.mongo;

import java.util.ArrayList;

import br.com.fatec.cqr.control.model.Comando;
import br.com.fatec.cqr.main.Principal;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;

public class Insert implements Comando {

	@Override
	public String conversao(String texto) {
		ArrayList<String> lista = new ArrayList<String>();
		ArrayList<String> listaAtributos = new ArrayList<String>();
		
		int indexOf = texto.indexOf("db.") + 3;
		int indexInsert = texto.indexOf(".insert");
		String tabela = texto.substring(indexOf, indexInsert);

		String retorno = "Comando executado: " + texto;
		int retirar = 0;

		String[] split = texto.split("\\(");
		for (int i = 1; i < split.length; i++) {

			split[i] = split[i].replaceAll("\\{", "");
			split[i] = split[i].replaceAll("\\}", "");
			String[] split2 = split[i].split(",|\\)");
			retirar = (i == 1) ? 1 : 0;

			for (int j = 0; j < split2.length; j++) {
				String[] split3 = split2[j].split(":");
				for (String item : split3) {
					listaAtributos.add(item.replaceAll("'", ""));
				}
			}
		}

			DBCollection coll = Principal.db.getCollection(tabela);

			BasicDBObject doc = new BasicDBObject();
			for (int k = 0; k < listaAtributos.size(); k+=2) {
				doc.append(listaAtributos.get(k), listaAtributos.get(k + 1));
			}

			coll.insert(doc);

			retorno += "\n\nInserido com sucesso.";

			return retorno;
		}

	@Override
	public String expressao() {
		return "^db.*\\.insert.*";
	}

}
